#include "unifiedthreadmanager.h"
#include <QDebug>
#include <QDateTime>
#include <QMutexLocker>
#include <QApplication>
#include <algorithm>
// TaskWrapper实现
TaskWrapper::TaskWrapper(std::shared_ptr<ITask> task, UnifiedThreadManager* manager)
    : m_task(task), m_manager(manager)
{
    setAutoDelete(true);
}
void TaskWrapper::run()
{
    if (!m_task || !m_manager) {
        return;
    }
    QString taskId = m_task->getTaskId();
    try {
        // 通知任务开始
        QMetaObject::invokeMethod(m_manager, "onTaskProgress", Qt::QueuedConnection,
                                Q_ARG(QString, taskId), Q_ARG(int, 0), Q_ARG(QString, "开始执行"));
        // 执行任务
        m_task->execute();
        // 通知任务完成
        QMetaObject::invokeMethod(m_manager, "onTaskCompleted", Qt::QueuedConnection,
                                Q_ARG(QString, taskId), Q_ARG(bool, true), Q_ARG(QString, QString()));
    } catch (const std::exception& e) {
        QString error = QString("任务执行异常: %1").arg(e.what());
        // 通知任务失败
        QMetaObject::invokeMethod(m_manager, "onTaskCompleted", Qt::QueuedConnection,
                                Q_ARG(QString, taskId), Q_ARG(bool, false), Q_ARG(QString, error));
    } catch (...) {
        QString error = "未知异常";
        // 通知任务失败
        QMetaObject::invokeMethod(m_manager, "onTaskCompleted", Qt::QueuedConnection,
                                Q_ARG(QString, taskId), Q_ARG(bool, false), Q_ARG(QString, error));
    }
}
// UnifiedThreadManager实现
UnifiedThreadManager* UnifiedThreadManager::s_instance = nullptr;
QMutex UnifiedThreadManager::s_instanceMutex;
UnifiedThreadManager::UnifiedThreadManager(QObject* parent)
    : QObject(parent)
    , m_threadPool(std::make_unique<QThreadPool>(this))
    , m_resourceMonitor(SystemResourceMonitor::instance())
    , m_strategy(SchedulingStrategy::Adaptive)
    , m_maxConcurrentTasks(0) // 0表示使用自动计算
    , m_memoryLimit(0) // 0表示无限制
    , m_adaptiveSchedulingEnabled(true)
    , m_schedulingPaused(false)
    , m_queueProcessTimer(new QTimer(this))
    , m_resourceAdjustTimer(new QTimer(this))
{
    initializeThreadPool();
    startTimers();
    // 连接资源监控信号
    connect(m_resourceMonitor, &SystemResourceMonitor::resourceUpdated,
            this, &UnifiedThreadManager::onResourceUpdated);
    // 启动资源监控
    m_resourceMonitor->startMonitoring(2000); // 2秒间隔
}
UnifiedThreadManager::~UnifiedThreadManager()
{
    stopTimers();
    // 等待所有任务完成
    m_threadPool->waitForDone(5000); // 最多等待5秒
    // 清理观察者
    {
        QMutexLocker locker(&m_observersMutex);
        m_observers.clear();
    }
}
UnifiedThreadManager* UnifiedThreadManager::instance()
{
    QMutexLocker locker(&s_instanceMutex);
    if (!s_instance) {
        s_instance = new UnifiedThreadManager();
    }
    return s_instance;
}
bool UnifiedThreadManager::submitTask(std::shared_ptr<ITask> task)
{
    if (!task) {
        return false;
    }
    QString taskId = task->getTaskId();
    QMutexLocker locker(&m_tasksMutex);
    // 检查任务是否已存在
    if (m_allTasks.contains(taskId)) {
        return false;
    }
    // 添加到队列和任务记录
    m_taskQueue.enqueue(task);
    m_allTasks[taskId] = TaskInfo(task);
    // 发送状态变化信号
    emit taskStatusChanged(taskId, TaskStatus::Queued);
    return true;
}
bool UnifiedThreadManager::cancelTask(const QString& taskId)
{
    QMutexLocker locker(&m_tasksMutex);
    // 检查任务是否存在
    if (!m_allTasks.contains(taskId)) {
        return false;
    }
    TaskInfo& taskInfo = m_allTasks[taskId];
    // 如果任务正在运行，尝试取消
    if (taskInfo.status == TaskStatus::Running) {
        if (m_runningTasks.contains(taskId)) {
            auto task = m_runningTasks[taskId];
            if (task->isCancellable()) {
                task->cancel();
                updateTaskStatus(taskId, TaskStatus::Cancelled);
                m_runningTasks.remove(taskId);
                notifyTaskCancelled(taskId);
                return true;
            } else {
                return false;
            }
        }
    }
    // 如果任务在队列中，直接移除
    if (taskInfo.status == TaskStatus::Queued) {
        // 从队列中移除任务（需要重建队列）
        QQueue<std::shared_ptr<ITask>> newQueue;
        while (!m_taskQueue.isEmpty()) {
            auto task = m_taskQueue.dequeue();
            if (task->getTaskId() != taskId) {
                newQueue.enqueue(task);
            }
        }
        m_taskQueue = newQueue;
        updateTaskStatus(taskId, TaskStatus::Cancelled);
        notifyTaskCancelled(taskId);
        return true;
    }
    return false;
}
void UnifiedThreadManager::pauseScheduling()
{
    m_schedulingPaused = true;
}
void UnifiedThreadManager::resumeScheduling()
{
    m_schedulingPaused = false;
}
void UnifiedThreadManager::addProgressObserver(IProgressObserver* observer)
{
    if (!observer) return;
    QMutexLocker locker(&m_observersMutex);
    if (!m_observers.contains(observer)) {
        m_observers.append(observer);
    }
}
void UnifiedThreadManager::removeProgressObserver(IProgressObserver* observer)
{
    if (!observer) return;
    QMutexLocker locker(&m_observersMutex);
    m_observers.removeAll(observer);
}
void UnifiedThreadManager::setSchedulingStrategy(SchedulingStrategy strategy)
{
    m_strategy = strategy;
}
void UnifiedThreadManager::setMaxConcurrentTasks(int maxTasks)
{
    m_maxConcurrentTasks = maxTasks;
    if (maxTasks > 0) {
        m_threadPool->setMaxThreadCount(maxTasks);
    }
}
void UnifiedThreadManager::setMemoryLimit(qint64 memoryLimit)
{
    m_memoryLimit = memoryLimit;
}
void UnifiedThreadManager::enableAdaptiveScheduling(bool enabled)
{
    m_adaptiveSchedulingEnabled = enabled;
}
UnifiedThreadManager::TaskInfo UnifiedThreadManager::getTaskInfo(const QString& taskId) const
{
    QMutexLocker locker(&m_tasksMutex);
    return m_allTasks.value(taskId);
}
QList<UnifiedThreadManager::TaskInfo> UnifiedThreadManager::getAllTasks() const
{
    QMutexLocker locker(&m_tasksMutex);
    return m_allTasks.values();
}
int UnifiedThreadManager::getQueuedTaskCount() const
{
    QMutexLocker locker(&m_tasksMutex);
    return m_taskQueue.size();
}
int UnifiedThreadManager::getRunningTaskCount() const
{
    QMutexLocker locker(&m_tasksMutex);
    return m_runningTasks.size();
}
int UnifiedThreadManager::getCompletedTaskCount() const
{
    QMutexLocker locker(&m_tasksMutex);
    int count = 0;
    for (const auto& taskInfo : m_allTasks) {
        if (taskInfo.status == TaskStatus::Completed) {
            count++;
        }
    }
    return count;
}
void UnifiedThreadManager::clearCompletedTasks()
{
    QMutexLocker locker(&m_tasksMutex);
    auto it = m_allTasks.begin();
    while (it != m_allTasks.end()) {
        if (it.value().status == TaskStatus::Completed || 
            it.value().status == TaskStatus::Failed ||
            it.value().status == TaskStatus::Cancelled) {
            it = m_allTasks.erase(it);
        } else {
            ++it;
        }
    }
}
void UnifiedThreadManager::onTaskCompleted(const QString& taskId, bool successful, const QString& errorMessage)
{
    QMutexLocker locker(&m_tasksMutex);
    // 从运行任务中移除
    m_runningTasks.remove(taskId);
    // 更新任务状态
    if (successful) {
        updateTaskStatus(taskId, TaskStatus::Completed);
        notifyTaskCompleted(taskId);
    } else {
        updateTaskStatus(taskId, TaskStatus::Failed, errorMessage);
        notifyTaskFailed(taskId, errorMessage);
    }
    // 发送线程池状态更新信号
    emit threadPoolStatusChanged(m_threadPool->activeThreadCount(), m_threadPool->maxThreadCount());
}
void UnifiedThreadManager::onTaskProgress(const QString& taskId, int progress, const QString& status)
{
    notifyObservers(taskId, progress, status);
}
void UnifiedThreadManager::processQueue()
{
    if (m_schedulingPaused) {
        return;
    }
    QMutexLocker locker(&m_tasksMutex);
    // 检查是否有可执行的任务
    while (!m_taskQueue.isEmpty() && m_threadPool->activeThreadCount() < m_threadPool->maxThreadCount()) {
        auto task = selectNextTask();
        if (!task) {
            break;
        }
        if (canExecuteTask(task)) {
            executeTask(task);
        } else {
            // 如果无法执行，重新加入队列
            m_taskQueue.enqueue(task);
            break;
        }
    }
}
void UnifiedThreadManager::adjustResourceAllocation()
{
    if (!m_adaptiveSchedulingEnabled) {
        return;
    }
    auto resourceInfo = m_resourceMonitor->getCurrentResources();
    // 计算最优线程数
    int queuedTasks = getQueuedTaskCount();
    if (queuedTasks > 0) {
        // 估算平均任务内存使用量
        qint64 avgMemoryPerTask = 100 * 1024 * 1024; // 默认100MB
        {
            QMutexLocker locker(&m_tasksMutex);
            if (!m_taskQueue.isEmpty()) {
                qint64 totalMemory = 0;
                int taskCount = 0;
                // 计算队列中任务的平均内存需求
                for (const auto& task : m_taskQueue) {
                    totalMemory += task->getEstimatedMemory();
                    taskCount++;
                }
                if (taskCount > 0) {
                    avgMemoryPerTask = totalMemory / taskCount;
                }
            }
        }
        int optimalThreads = m_resourceMonitor->getOptimalThreadCount(queuedTasks, avgMemoryPerTask);
        // 如果没有设置最大并发任务数，使用计算出的最优值
        if (m_maxConcurrentTasks == 0) {
            m_threadPool->setMaxThreadCount(optimalThreads);
            emit threadPoolStatusChanged(m_threadPool->activeThreadCount(), m_threadPool->maxThreadCount());
        }
    }
}
void UnifiedThreadManager::onResourceUpdated(const SystemResourceMonitor::ResourceInfo& info)
{
    // 资源更新时的处理逻辑
    Q_UNUSED(info)
    // 可以在这里添加基于资源状态的调度调整逻辑
}
void UnifiedThreadManager::initializeThreadPool()
{
    // 设置线程池的初始参数
    int initialThreadCount = QThread::idealThreadCount();
    m_threadPool->setMaxThreadCount(initialThreadCount);
}
void UnifiedThreadManager::startTimers()
{
    // 队列处理定时器
    connect(m_queueProcessTimer, &QTimer::timeout, this, &UnifiedThreadManager::processQueue);
    m_queueProcessTimer->start(100); // 100ms间隔处理队列
    // 资源调整定时器
    connect(m_resourceAdjustTimer, &QTimer::timeout, this, &UnifiedThreadManager::adjustResourceAllocation);
    m_resourceAdjustTimer->start(5000); // 5秒间隔调整资源
}
void UnifiedThreadManager::stopTimers()
{
    if (m_queueProcessTimer) {
        m_queueProcessTimer->stop();
    }
    if (m_resourceAdjustTimer) {
        m_resourceAdjustTimer->stop();
    }
}
std::shared_ptr<ITask> UnifiedThreadManager::selectNextTask()
{
    if (m_taskQueue.isEmpty()) {
        return nullptr;
    }
    switch (m_strategy) {
        case SchedulingStrategy::FIFO:
            return selectTaskFIFO();
        case SchedulingStrategy::Priority:
            return selectTaskByPriority();
        case SchedulingStrategy::LoadBalanced:
            return selectTaskLoadBalanced();
        case SchedulingStrategy::Adaptive:
            return selectTaskAdaptive();
        default:
            return selectTaskFIFO();
    }
}
std::shared_ptr<ITask> UnifiedThreadManager::selectTaskFIFO()
{
    return m_taskQueue.dequeue();
}
std::shared_ptr<ITask> UnifiedThreadManager::selectTaskByPriority()
{
    if (m_taskQueue.isEmpty()) return nullptr;
    // 找到优先级最高的任务
    auto bestTask = m_taskQueue.first();
    int bestIndex = 0;
    for (int i = 1; i < m_taskQueue.size(); ++i) {
        auto task = m_taskQueue[i];
        if (task->getPriority() > bestTask->getPriority()) {
            bestTask = task;
            bestIndex = i;
        }
    }
    // 从队列中移除选中的任务
    QQueue<std::shared_ptr<ITask>> newQueue;
    for (int i = 0; i < m_taskQueue.size(); ++i) {
        if (i != bestIndex) {
            newQueue.enqueue(m_taskQueue[i]);
        }
    }
    m_taskQueue = newQueue;
    return bestTask;
}
std::shared_ptr<ITask> UnifiedThreadManager::selectTaskLoadBalanced()
{
    // 简化实现：基于内存使用量选择任务
    if (m_taskQueue.isEmpty()) return nullptr;
    auto resourceInfo = m_resourceMonitor->getCurrentResources();
    qint64 availableMemory = resourceInfo.availableMemory;
    // 选择内存需求最小的任务
    auto bestTask = m_taskQueue.first();
    int bestIndex = 0;
    for (int i = 1; i < m_taskQueue.size(); ++i) {
        auto task = m_taskQueue[i];
        if (task->getEstimatedMemory() <= availableMemory &&
            task->getEstimatedMemory() < bestTask->getEstimatedMemory()) {
            bestTask = task;
            bestIndex = i;
        }
    }
    // 从队列中移除选中的任务
    QQueue<std::shared_ptr<ITask>> newQueue;
    for (int i = 0; i < m_taskQueue.size(); ++i) {
        if (i != bestIndex) {
            newQueue.enqueue(m_taskQueue[i]);
        }
    }
    m_taskQueue = newQueue;
    return bestTask;
}
std::shared_ptr<ITask> UnifiedThreadManager::selectTaskAdaptive()
{
    // 自适应调度：综合考虑优先级、资源需求和等待时间
    if (m_taskQueue.isEmpty()) return nullptr;
    auto resourceInfo = m_resourceMonitor->getCurrentResources();
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    auto bestTask = m_taskQueue.first();
    int bestIndex = 0;
    double bestScore = -1.0;
    for (int i = 0; i < m_taskQueue.size(); ++i) {
        auto task = m_taskQueue[i];
        // 计算综合评分
        double priorityScore = static_cast<double>(task->getPriority()) / 10.0;
        // 等待时间奖励
        qint64 waitTime = currentTime - m_allTasks[task->getTaskId()].queueTime.toMSecsSinceEpoch();
        double waitScore = std::min(waitTime / 60000.0, 1.0); // 最多1分钟的等待奖励
        // 资源适配性
        double resourceScore = 1.0;
        if (task->getEstimatedMemory() > resourceInfo.availableMemory) {
            resourceScore = 0.1; // 内存不足时大幅降低评分
        }
        double totalScore = priorityScore + waitScore + resourceScore;
        if (totalScore > bestScore) {
            bestTask = task;
            bestIndex = i;
            bestScore = totalScore;
        }
    }
    // 从队列中移除选中的任务
    QQueue<std::shared_ptr<ITask>> newQueue;
    for (int i = 0; i < m_taskQueue.size(); ++i) {
        if (i != bestIndex) {
            newQueue.enqueue(m_taskQueue[i]);
        }
    }
    m_taskQueue = newQueue;
    return bestTask;
}
bool UnifiedThreadManager::canExecuteTask(std::shared_ptr<ITask> task)
{
    if (!task) return false;
    // 检查内存限制
    if (m_memoryLimit > 0 && task->getEstimatedMemory() > m_memoryLimit) {
        return false;
    }
    // 检查系统资源
    auto resourceInfo = m_resourceMonitor->getCurrentResources();
    if (task->getEstimatedMemory() > resourceInfo.availableMemory * 0.9) { // 保留10%内存
        return false;
    }
    return true;
}
void UnifiedThreadManager::executeTask(std::shared_ptr<ITask> task)
{
    if (!task) return;
    QString taskId = task->getTaskId();
    // 添加到运行任务列表
    m_runningTasks[taskId] = task;
    // 更新任务状态
    updateTaskStatus(taskId, TaskStatus::Running);
    // 通知任务开始
    notifyTaskStarted(taskId);
    // 创建任务包装器并提交到线程池
    TaskWrapper* wrapper = new TaskWrapper(task, this);
    m_threadPool->start(wrapper);
    // 发送线程池状态更新信号
    emit threadPoolStatusChanged(m_threadPool->activeThreadCount(), m_threadPool->maxThreadCount());
}
void UnifiedThreadManager::notifyObservers(const QString& taskId, int progress, const QString& status)
{
    QMutexLocker locker(&m_observersMutex);
    for (auto observer : m_observers) {
        observer->onProgressUpdated(taskId, progress, status);
    }
}
void UnifiedThreadManager::notifyTaskCompleted(const QString& taskId)
{
    QMutexLocker locker(&m_observersMutex);
    for (auto observer : m_observers) {
        observer->onTaskCompleted(taskId);
    }
}
void UnifiedThreadManager::notifyTaskFailed(const QString& taskId, const QString& error)
{
    QMutexLocker locker(&m_observersMutex);
    for (auto observer : m_observers) {
        observer->onTaskFailed(taskId, error);
    }
}
void UnifiedThreadManager::notifyTaskStarted(const QString& taskId)
{
    QMutexLocker locker(&m_observersMutex);
    for (auto observer : m_observers) {
        observer->onTaskStarted(taskId);
    }
}
void UnifiedThreadManager::notifyTaskCancelled(const QString& taskId)
{
    QMutexLocker locker(&m_observersMutex);
    for (auto observer : m_observers) {
        observer->onTaskCancelled(taskId);
    }
}
void UnifiedThreadManager::updateTaskStatus(const QString& taskId, TaskStatus status, const QString& errorMessage)
{
    if (m_allTasks.contains(taskId)) {
        TaskInfo& taskInfo = m_allTasks[taskId];
        taskInfo.status = status;
        taskInfo.errorMessage = errorMessage;
        QDateTime now = QDateTime::currentDateTime();
        if (status == TaskStatus::Running) {
            taskInfo.startTime = now;
        } else if (status == TaskStatus::Completed || status == TaskStatus::Failed || status == TaskStatus::Cancelled) {
            taskInfo.endTime = now;
        }
        emit taskStatusChanged(taskId, status);
    }
}
